package com.example.chessbattleplatform.utils;

import com.example.chessbattleplatform.Pojo.Exception.BusinessException;
import com.example.chessbattleplatform.Pojo.Exception.StatusCode;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class ThreadJwtParseUtils {
    private final JwtUtils jwtUtils;

    public String getStrThreadUserId() {
        String userToken = UserIdThreadLocalStorage.getUserToken();
        return getTokenToUserId(userToken);
    }
    public Long getThreadUserId() {
        String userToken = UserIdThreadLocalStorage.getUserToken();
        return Long.valueOf(getTokenToUserId(userToken));
    }
    public String getTokenToUserId(String userToken) {
        Claims claims = jwtUtils.parseJWT(userToken);
        if (claims == null) {
            throw new BusinessException(StatusCode.UNAUTHORIZED, "token验证失败");
        }
        return claims.get("uid").toString();
    }

    public String getThreadParsePassword() {
        String userToken = UserIdThreadLocalStorage.getUserToken();
        return getTokenToParsePassword(userToken);
    }

    public String getTokenToParsePassword(String userToken) {
        Claims claims = jwtUtils.parseJWT(userToken);
        if (claims == null) {
            throw new BusinessException(StatusCode.UNAUTHORIZED, "token验证失败");
        }

        return claims.get("pwd").toString();
    }
}
